# -*- coding: utf-8 -*-
'''eof
name:借款人半年内逾期次数
code:R07_IC_OvduSixMonsCheck_WHB_2D
tableName:
columnName:
groups:弱规则>个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''


from __future__ import division
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import datetime
import pandas as pd
from dateutil.parser import parse

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
    获取表信息
    :param data:表上层的字典对象
    :param tableName:表的名字
    :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
    :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
    :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def intCheck(str):
    try:
        int(str)
        return True
    except:
        return False

def getCount(statusList, min, max, endMonth=None, type=1, deltaMonth=6):
    '''
    Explanation
    ------------
    计算某个特定时间范围内的累计逾期次数
    
    parameters
    ------------
    statusList:list
        该指标内指两年、五年还款信息列表
    min:int,float形式的整数
        最小逾期月份数
    max:int,float形式的整数
        最大逾期月份数
    endMonth:str,时间形式的字符串，如2021-12,2021/12,2021.12;年份与月份之间必须有符号
        以该时间节点为考察范围的右边界
    type:int,float形式的整数
        用于判断使用两年还是五年还款信息表
    deltaMonth:int,float形式的整数
        确认考察范围的长度，配合参数endMonth-deltaMonth，得到左边界

    return
    -----------
    result:float(-1或正常值，-1为报错情况)
        单个账户的累计逾期次数
    '''
    if statusList in null_type_list:
        return -1
    
    if type == 1:
        stateStr = 'PD01DD01' # 24个月还款状态
        monthStr = 'PD01DR03' # 月份
    else:
        stateStr = 'PD01ED01' # 五年的还款状态
        monthStr = 'PD01ER03' # 月份
    if endMonth is None:
        # 使用当前时间为阈值
        endMonthStr = datetime.datetime.now().strftime("%Y-%m-%d")
        endMonthFact = float(endMonthStr[:4]) * 12 + float(endMonthStr[5:7]) #将当前时间划分为月份数，取整法
    else:
        try:
            # 使用传入的截止日期计算阈值，就是说只看某个特定时间之前的逾期记录
            endMonthFact = float(endMonth[:4]) * 12 + float(endMonth[5:7]) if len(endMonth) >= 6 else None
            if endMonthFact is None:
                return -1    
        except:
            return -1
    # 往前推deltaMonth
    month6AgoFact = endMonthFact - deltaMonth
    result = 0
    flag = False  
    for i in statusList:
        try:
            state = i.get(stateStr)
            month = i.get(monthStr)
            monthFact = float(month[:4]) * 12 + float(month[5:7])
            if state not in null_type_list:
                flag = True               
            if ((intCheck(state) and min <= int(state) <= max)) and month6AgoFact < monthFact <= endMonthFact :
                result += 1
        except:
            continue
    if flag:
        return result
    else:
        return -1

def checkNull(data, accountType):
    '''若最近24个月还款状态信息为空，返回结果为缺失值，则进行以下逻辑判断：
    1.基本信息段（PD01A）-账户类型（PD01AD01）为D1，若最新表现信息段（PD01B）-账户状态（PD01BD01）为3（结清）且关闭日期（PD01BR01）＞5年或账户状态（PD01BD01）为5（转出）且转出月份（PD01BR04）＞5年，则Factor=1,否则Factor=缺失值；
    2.基本信息段（PD01A）-账户类型（PD01AD01）为R1、R4，若最新表现信息段（PD01B）-账户状态（PD01BD01）为3（结清）且关闭日期（PD01BR01）＞5年，则Factor=1,否则Factor=缺失值；
    '''
    if data in null_type_list or data == [{}] or data == 0:
        return 0
    # 账户状态
    PD01BD01 = data[0].get("PD01BD01")
    # 关闭日期
    PD01BR01 = data[0].get("PD01BR01")
    PD01BR01 = dateFormat(PD01BR01)
    # 转出月份
    PD01BR04 = data[0].get("PD01BR04")
    PD01BR04 = dateFormat(PD01BR04)
    fiveYearsAgo = datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=5)
    if accountType == "D1":
        if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01 < fiveYearsAgo)\
                or (PD01BD01 == "5" and PD01BR04 is not None and PD01BR04 < fiveYearsAgo):
            return 1
        else:
            return 0
    elif accountType in ["R1", "R4"]:
        if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01 < fiveYearsAgo):
            return 1
        else:
            return 0
    else:
        return 0

def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

# 仅使用五年逾期记录计算
def R07_IC_OvduSixMonsCheck_WHB_2D():
    data = IC_DSJ_2D['data']
    # 借贷账户信息
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            factor = []
            for i in PD01:
                try:
                    # 基本信息段
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    if PD01A == [{}]:
                        factor.append(None)
                    elif PD01A == 0:
                        factor.append(0)
                    else:
                        # 账户类型
                        PD01AD01 = PD01A[0].get("PD01AD01")
                        if PD01AD01 not in null_type_list:
                            if PD01AD01 == "D1" or PD01AD01 == "R1" or PD01AD01 == "R4":
                                # 最新表现信息段  PD01B  [1..1]
                                PD01B = getTable(i, 'PD01B', 1, 1)
                                # 最近一次月度表现信息段 PD01C  [0..1]
                                PD01C = getTable(i, 'PD01C', 0, 1)
                                # 最近 5 年内的历史表现信息段
                                PD01E = getTable(i, 'PD01E', 0, 1)
                                if PD01E == [{}] or PD01B == [{}]:
                                    factor.append(None)
                                elif PD01E == 0 or PD01B == 0:
                                    factor.append(0)
                                else:
                                    # 截止年月：
                                    PD01ER02 = PD01E[0].get('PD01ER02')
                                    # 历史表现信息 PD01EH
                                    PD01EH = PD01E[0].get('PD01EH')
                                    if PD01EH == None:
                                        try:
                                            reportTime = parse(data['PRH'][0]['PA01'][0]['PA01A'][0]['PA01AR01'])
                                            deadLineTime = parse(PD01C[0]['PD01CR04'])
                                            if (reportTime - deadLineTime).days/365 > 5:
                                                factor.append(0)
                                            else:
                                                factor.append(None)
                                        except:  
                                            factor.append(None)
                                    else:
                                        # 最新表现信息中的账户状态
                                        PD01BD01 = PD01B[0].get('PD01BD01')
                                        # 最近一次月度表现中的账户状态
                                        PD01CD01 = PD01C[0].get('PD01CD01')
                                        if PD01BD01 in null_type_list and PD01CD01 in null_type_list:
                                            factor.append(None)
                                        elif PD01BD01 not in null_type_list:
                                            if PD01BD01 in ['1', '2']:
                                                # 未结清使用截止日期判断
                                                count = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2, deltaMonth=6)
                                            else:
                                                # 已结清使用当前时间判断
                                                count = getCount(PD01EH, min=1, max=7, endMonth=None, type=2, deltaMonth=6)
                                                
                                            if count == -1:
                                                checkRes = checkNull(PD01B, PD01AD01)
                                                if checkRes:
                                                    factor.append(0)
                                                else:
                                                    factor.append("None")
                                            else:
                                                factor.append(count)
                                        else:
                                            if PD01CD01 in ['1', '2']:
                                                # 未结清使用截止日期判断
                                                count = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2, deltaMonth=6)
                                            else:
                                                # 已结清使用当前时间判断
                                                count = getCount(PD01EH, min=1, max=7, endMonth=None, type=2, deltaMonth=6)
                                                
                                            if count == -1:
                                                checkRes = checkNull(PD01C, PD01AD01)
                                                if checkRes:
                                                    factor.append(0)
                                                else:
                                                    factor.append("None")
                                            else:
                                                factor.append(count)
                            else:
                                factor.append(0)
                        else:
                            factor.append(None)
                except:
                    factor.append(None)
        if "None" in factor:
            return u'缺失值'
        factor = filter(lambda x:x is not None, factor)
        if len(factor) == 0:
            return u'缺失值'
        else:
            factor = filter(lambda x:x != 0, factor)
            return sum(factor)

result = R07_IC_OvduSixMonsCheck_WHB_2D()
